package cn.kgc.javaweb.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Author: 课工场
 * @Version: v1.0  2023/5/18
 * @Description:  非法请求拦截
 *
 * Filter生命周期
 * 创建的时机   服务器启动
 * init()   对象创建完毕 自动调用
 */
@WebFilter("/*")
public class LoginFilter implements Filter {

    //  服务器启动时调用  只调用一次
    public LoginFilter(){
        System.out.println("============LoginFilter()=============");
    }

    // 初始化方法  只调用一次
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    // 过滤方法
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        req.setCharacterEncoding("utf-8");
        HttpServletResponse resp = (HttpServletResponse) response;

        // 放行资源  login.jsp      register.jsp
        String servletPath = req.getServletPath();
        if("/login.jsp".equals(servletPath) || "/register.jsp".equals(servletPath)){
            chain.doFilter(req, resp);
            return;
        }

        //    /user?method=login    /user?method=register
        String method = req.getParameter("method");
        if("login".equals(method) || "register".equals(method) ){
            chain.doFilter(req, resp);
            return;
        }

        //  验证码  /captcha
        if(servletPath.equals("/captcha")){
            chain.doFilter(req, resp);
            return;
        }
        //  .css  .js
        if(servletPath.startsWith("/layui")){
            chain.doFilter(req, resp);
            return;
        }

        // 判定用户是否是合法用户  登录
        HttpSession session = req.getSession();
        Object user = session.getAttribute("user");

        if(user==null){  //  用户没登录
            resp.sendRedirect(req.getContextPath()+"/login.jsp");
            return;
        }
        // 放行请求
        chain.doFilter(req, resp);
    }

    // 销毁方法  只调用一次 服务器关闭
    @Override
    public void destroy() {
        System.out.println("============destroy()=============");
    }
}
